'''
@Project ：pythonApiTest 
@File    ：TestRunner.py
@IDE     ：PyCharm 
@Author  ：胡文
@Date    ：2025/2/28 上午9:36 
'''

import requests
from requests.adapters import HTTPAdapter


class TestRunner:
    def __init__(self):
        self.session = requests.Session()
        self.session.mount('http://', HTTPAdapter(max_retries=3))

    def execute_case(self, case):
        try:
            # 处理动态参数（如从前置条件获取token）
            if case['precondition']:
                self._handle_precondition(case['precondition'])

            response = self.session.request(
                method=case['method'],
                url=f"{config.BASE_URL}{case['path']}",
                json=case['params']
            )

            # 断言验证
            assert_result = {
                "status_code": response.status_code == case['expected_status'],
                "response_body": self._compare_json(
                    response.json(),
                    case['expected_response']
                )
            }
            return response, assert_result
        except Exception as e:
            return None, {"error": str(e)}